package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"soc-ecom-mgr/cache"
	"soc-ecom-mgr/model"
	"soc-ecom-mgr/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不为空",
		})
		return
	}

	var user model.User
	err := model.DB.Where("username = ? and password = ?", username, pkg.Md5Str(password)).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "登录失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录成功",
		})
		return
	}

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	img := c.PostForm("img")

	if title == "" || content == "" || img == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}

	data := model.Book{
		Title:   title,
		Content: content,
		Img:     img,
	}
	err := model.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}

	//设置缓存
	redis_key := "book_id_" + strconv.Itoa(int(data.ID))
	var book model.Book
	model.DB.Where("id = ?", data.ID).First(&book)
	jsonData, _ := json.Marshal(book)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
		"data": book,
	})
	return

}
func List(c *gin.Context) {
	var book []model.Book

	redis_key := "book_list"

	jsonData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if jsonData == "" {
		model.DB.Find(&book)
		jsonData, _ := json.Marshal(book)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	} else {
		json.Unmarshal([]byte(jsonData), &book)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": book,
	})
	return

}
func Del(c *gin.Context) {
	id := c.Query("id")
	model.DB.Where("id = ?", id).First(&model.Book{})
	redis_key := "book_id" + id
	cache.Rdb.Del(cache.Ctx, redis_key)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return

}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var book model.Book
	model.DB.Where("id = ?", id).First(&book)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": book,
	})
	return
}
